<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<title></title>
		<link rel="stylesheet" type="text/css" href="common/css/semantic.css" />
		<link rel="stylesheet" type="text/css" href="common/css/caf.css" />
		<link rel="stylesheet" type="text/css" href="common/css/default.css" />
		<link rel="stylesheet" type="text/css" href="common/css/swiper-3.4.0.min.css" />
		<link rel="stylesheet" type="text/css" href="common/font/iconfont.css" />
		<link rel="stylesheet" type="text/css" href="common/css/common.css" />
		<script type="text/javascript" src="plugin/jquery/jquery-1.7.2.min.js"></script>
		<script src="plugin/require/require.js" data-main="main"></script>

		<style>
			html, body {
				width: 100%;
				height: 100%;
			}
			.loading {
				position: fixed;
				top: 0;
				left: 0;
				right: 0;
				background: rgba(0,0,0,0.2);
				z-index: 100;
				display: none;
			}
			.loading img {
				width: 40px;
				height: 40px;
				position: fixed;
				top: 50%;
				left: 50%;
				transform: translate(-50%,-50%);
				-webkit-transform: translate(-50%,-50%);
				-moz-transform: translate(-50%,-50%);
				-ms-transform: translate(-50%,-50%);
				-o-transform: translate(-50%,-50%);
			}
		</style>
	</head>

	<body ms-controller="root">
		<div ms-html="content" style="width:100%;height:100%;"></div>
		<div class="loading" id="loading">
			<img src="modules/img/load.gif" />
		</div>
	</body>
	<script type="text/javascript">
		jQuery(document).ready(function() {
			//window.setTimeout(init, 1000);
		})
		function init() {
			document.addEventListener("deviceready", init, false);
		}

		function init() {
			try {
				//window.StatusBar.backgroundColorByHexString("#3A89C2");
				//window.StatusBar.backgroundColorByName("#3A89C2");
				document.addEventListener("backbutton", onBackKeyDown, false);

				//检查app 版本更新
				checkUpdate();
			} catch(e) {
				alert(e)
			}
		}

		var deviceready = function() {
			try {
				window.StatusBar.backgroundColorByHexString("#3A89C2");
				window.StatusBar.backgroundColorByName("#3A89C2");
				document.addEventListener("backbutton", onBackKeyDown, false);

				//检查app 版本更新
				checkUpdate();
			} catch(e) {
				alert(e)
			}
		};
		function scanCode(num, id) {
			try {
				cordova.plugins.barcodeScanner.scan(function(result) {
					setstorage('code', result.text);
					if (result.text) {
						var code = result.text;
						bindCode(code, id);
					} else {
						if (num == 2) {
							Router.go('/result/result');
						} else if (num == 1) {
							Router.go('/Home/Home');
						}
					}
				}, function(error) {
					console.log("Scanning failed: " + error);
				})
			} catch(e) {
				console.log(e)
			}
		}

		var getRegistrationID = function() {
			JPush.init();
			JPush.getRegistrationID(onGetRegistrationID);
		};

		var onGetRegistrationID = function(data) {
			try {
				loginData(data);
			} catch(exception) {
				console.log(exception);
			}
		};

		var initiateUI = function() {
			try {
				window.setTimeout(getRegistrationID, 1000);
			} catch(exception) {
				console.log(exception);
			}
		};

		function backHome() {
			Router.go('/Home/Home');
		}

		function loginData(data) {
			httpPost('web/loginDev', {
				deviceId : data,
				deviceinfo : '1',
			}).done(function(data) {
				if ("200" == data.code) {
					console.log(data.token);
					setstorage('token', data.token);
					setstorage('user', data.user);
					Router.go('/Home/Home');
				} else {
					msgbox('提示', data.msg);
				}
			});
		}

		function bindCode(code, id) {
			//			var user=JSON.parse(getstorage('user'))
			httpPost('userDevice/bindUserandDevice', {
				userId : id,
				device_sn : code
			}).done(function(data) {
				if ("200" == data.code) {
					msgbox('提示', '绑定设备成功', 'backHome()', 1, 0);
				} else {
					msgbox('提示', data.msg);
				}
			});
		}

		var flag = 0;
		function wxlogin() {
			$('#loadPic').show();
			if(flag==0){
				flag = 1;
				wx();
				flag = 0;
			}else{
				window.plugins.toast.show('正在进行微信登录......', 'long', 'center');
			}
			$('#loadPic').hide();
		}
		
		
		//微信登录
		function wx() {
			$('#loadPic').hide();
			Wechat.isInstalled(function(installed) {
				JPush.init();
				if (installed) {
					var scope = "snsapi_userinfo", state = "_" + (+new Date());
					Wechat.auth(scope, state, function(response) {
						// you may use response.code to get the access token.
						//缓冲开始 正在登录......,请稍后
						window.plugins.toast.show('授权成功,正在跳到登录操作......', 'long', 'center');

						JPush.getRegistrationID(function(data) {
							try {
								httpPost('web/loginWX', {
									code : response.code,
									deviceId : data,
									deviceInfo : '1'
								}).done(function(data) {
									if ("200" == data.code) {
										setstorage('token', data.token);
										setstorage('user', data.user);
										Router.go('/Home/Home');
									} else {
										msgbox('提示', data.msg);
									}
								});
							} catch(exception) {
								msgbox('提示',exception);
							}
						});
					}, function(reason) {
						msgbox('提示', reason);
					});
				} else {
					msgbox('提示', "请安装微信!");
				}
			}, function(reason) {
				msgbox('提示', reason);
			});
		}

		function onBackKeyDown() {
			try {
				var url = location.hash;
				if (url == '#/Home/Home') {
					window.plugins.toast.show('再点击一次退出登录!', 'long', 'center');
					document.removeEventListener("backbutton", onBackKeyDown, false);
					// 注销返回键
					document.addEventListener("backbutton", exitLogin, false);
					//绑定退出事件
					// 3秒后重新注册
					var intervalID = window.setInterval(function() {
						window.clearInterval(intervalID);
						document.removeEventListener("backbutton", exitLogin, false);
						// 注销返回键
						document.addEventListener("backbutton", onBackKeyDown, false);
						// 返回键
					}, 3000);
				} else if (url == '#/start/start') {
					window.plugins.toast.show('再点击一次退出!', 'long', 'center');
					document.removeEventListener("backbutton", onBackKeyDown, false);
					// 注销返回键
					document.addEventListener("backbutton", exitApp, false);
					//绑定退出事件
					// 3秒后重新注册
					var intervalID = window.setInterval(function() {
						window.clearInterval(intervalID);
						document.removeEventListener("backbutton", exitApp, false);
						// 注销返回键
						document.addEventListener("backbutton", onBackKeyDown, false);
						// 返回键
					}, 3000);
				}
			} catch(e) {
				console.log(e)
			}

		}

		function exitApp() {
			navigator.app.exitApp();
		}

		function exitLogin() {
			Router.go("/start/start");
		}

		// 检查更新
		function checkUpdate() {
			try{
			}catch(e){alert(e)}
			
			// alert("x")
			// httpPost("check").done(function(result) {
				// alert(result)
				// var data = JSON.parse(result);
				// var serverAppVersion = data.versionName;
				// //从服务端获取最新版本
				// //获取版本
				// cordova.getAppVersion().then(function(version) {
					// //如果本地与服务端的APP版本不符合
					// if (version != serverAppVersion) {
						// showUpdateConfirm(data.changeLog + "[" + data.versionName + "]", data.apkUrl);
					// }
				// });
			// });
		}

		// 显示是否更新对话框
		function showUpdateConfirm(changeLog, apkUrl) {
			msgbox('版本升级', changeLog, update(changeLog, apkUrl), 1, cancelUpdate());
		}

		function cancelUpdate() {

		}

		function update(changeLog, apkUrl) {
			try {
				window.plugins.toast.show('已经下载：0%', 'long', 'center');
				var url = apkUrl;
				//可以从服务端获取更新APP的路径
				var targetPath = "file:///storage/sdcard0/Download/1.apk";
				//APP下载存放的路径，可以使用cordova file插件进行相关配置
				var trustHosts = true
				var options = {};
				downloadFile(url, targetPath, options, trustHosts);
				// downloadFile(url, targetPath, options, trustHosts).done(function(result) {
					// // 打开下载下来的APP
					// cordova.plugins.fileOpener2.open(targetPath, 'application/vnd.android.package-archive').then(function() {
						// // 成功
					// }, function(err) {
						// // 错误
					// });
					// window.plugins.toast.hide();
				// }
				// , function(err) {
					// window.plugins.toast.hide();
					// window.plugins.toast.show('下载失败!', 'long', 'center');
				// }, function(progress) {
					// //进度，这里使用文字显示下载百分比
					// window.setTimeout(function() {
						// var downloadProgress = (progress.loaded / progress.total) * 100;
						// window.plugins.toast.show("已经下载：" + Math.floor(downloadProgress) + "%", 'long', 'center');
						// if (downloadProgress > 99) {
							// window.plugins.toast.hide();
						// }
					// }, 1000)
				// }
				// );

			} catch(e) {
				alert(e)
			}
		}
		
		function downloadFile(source, filePath, options, trustAllHosts){
			try{
				alert("d")
			var q = $.Deferred();
	        var ft = new FileTransfer();
	        var uri = (options && options.encodeURI === false) ? source : encodeURI(source);
	
	        if (options && options.timeout !== undefined && options.timeout !== null) {
	          window.setTimeout(function () {
	            ft.abort();
	          }, options.timeout);
	          options.timeout = null;
	        }
	
	        ft.onprogress = function (progress) {
	          q.notify(function(progress) {
	          	window.plugins.toast.show('下载!', 'long', 'center');
					//进度，这里使用文字显示下载百分比
					window.setTimeout(function() {
						var downloadProgress = (progress.loaded / progress.total) * 100;
						window.plugins.toast.show("已经下载：" + Math.floor(downloadProgress) + "%", 'long', 'center');
						if (downloadProgress > 99) {
							window.plugins.toast.hide();
						}
					}, 1000)
				});
	        };
	
	        q.promise.abort = function () {
	          ft.abort();
	        };
	
	        ft.download(uri, filePath, q.resolve, q.reject, trustAllHosts, options);
	        }catch(e){alert(e)}
	        return q.promise;
		}
		
		function showPic(){
			$('#loadPic').show();
		}
		
		function hidePic(){
			$('#loadPic').hide();
		}

	</script>

</html>